// Copyright 2007 Google, Inc. All Rights Reserved.

package com.google.jessewilson.codesearch.ui;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;

/**
 * @author jessewilson
 */
public class Documents {

  /**
   * Return the character at the specified line, or -1 if that line is beyond
   * the end of the document.
   *
   * @param line, the line in the document, starting at 0
   * @return a value between 0 and document.length() inclusive if the line is
   *      found, or -1 if it is not.
   */
  public static int characterAtLine(Document document, int line)
      throws BadLocationException {
    for(int c = 0, currentLine = 0; true; c++) {
      if (currentLine == line) {
        return c;
      } else if(c > document.getLength()) {
        return -1;
      }

      if(c < document.getLength() && "\n".equals(document.getText(c, 1))) {
        currentLine++;
      }
    }
  }

}
